package com.ld.security.common.tomcat.anno.aop;

import com.ld.security.common.core.util.JsonUtil;
import com.ld.security.common.core.util.StringUtil;
import com.ld.security.common.core.util.TemplateUtil;
import com.ld.security.common.tomcat.anno.MockKey;
import com.ld.security.common.tomcat.util.RespUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Component
@Aspect
@Order(5)
public class MockAop {



    @Pointcut("@annotation(com.ld.security.common.tomcat.anno.MockKey)")
    public void aop() {

    }

   @Around("aop()")
    public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{
        Object val = pjp.proceed();
        if(val != null){
            return val;
        }
        String path="";
        String fileType="";
        Class clazz =  pjp.getTarget().getClass();
        MockKey parentKey =   AnnotationUtils.findAnnotation(clazz,MockKey.class);
        if(parentKey != null){
            path=parentKey.path();
        }
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        MockKey mockKey =  AnnotationUtils.findAnnotation(method, MockKey.class);

        fileType=mockKey.fileType();
        if(!StringUtil.isNull(mockKey.path())){
            path=path+mockKey.path();
        }

        String json = TemplateUtil.renderTemplate(path+"."+fileType,null);
        if(!StringUtil.isNull(mockKey.value())){
            Map map = JsonUtil.toObject(json,Map.class);
            val = map.get(mockKey.value());
        }
        RespUtil.writeJson(val);
        return null;
    }


}
